<template>
  <div>
    <div class="app-container" style="height: 100%">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入设备类型名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button type="primary" icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column
          prop="name"
          align="center"
          label="设备类型名称"
        ></el-table-column>
        <el-table-column
          prop="typeCode"
          align="center"
          label="设备类型编码"
        ></el-table-column>
        <el-table-column
          prop="dataFormType"
          align="center"
          label="系数"
        ></el-table-column>
        <el-table-column prop="type" align="center" label="设备类型">
          <template #default="scope">
            {{ getTypeName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="createAt"
          label="创建时间"
          sortable
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="createAt"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >

            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改图层对话框 -->
      <el-dialog
        :title="title"
        v-model="open"
        :width="form.id ? '800px' : '400px'"
        append-to-body
        destroy-on-close
      >
        <el-form ref="deptRef" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备类型名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入设备类型名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备类型编码" prop="typeCode">
                <el-input
                  v-model="form.typeCode"
                  placeholder="请输入设备类型编码"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="系数" prop="dataFormType">
                <el-input
                  v-model="form.dataFormType"
                  placeholder="请输入系数"
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="支持设备类型" prop="kind">
                <el-select v-model="form.type">
                  <el-option
                    v-for="item in deviceTypeEnumList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="form.id">
            <el-col :span="24">
              <el-form-item label="设备属性">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handlePropertyAdd"
                  >新增属性</el-button
                >
              </el-form-item>
              <div class="propertyList">
                <el-table
                  stripe
                  style="height: 400px; width: 100%"
                  :data="form.devicePropertyList"
                >
                  <el-table-column
                    align="center"
                    prop="name"
                    label="属性名称"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="dataCode"
                    label="属性编码"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    :filters="[
                      { text: '硬件属性', value: 0 },
                      { text: '数据属性', value: 1 },
                    ]"
                    :filter-method="filterTag"
                    prop="kind"
                    label="属性类型"
                  >
                    <template #default="scope">
                      {{ scope.row.kind == 0 ? "硬件属性" : "数据属性" }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="dataType"
                    label="属性数据类型"
                  >
                    <template #default="scope">
                      {{ getNameByType(scope.row.dataType) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="statType"
                    label="统计类型"
                  >
                    <template #default="scope">
                      {{ getStatNameByType(scope.row.statType) }}
                    </template>
                  </el-table-column>
                  
                  <el-table-column
                    align="center"
                    prop="dataFormContent"
                    label="属性默认值"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="dataDw"
                    label="属性单位"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="dataMultiple"
                    label="系数"
                  >
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    align="center"
                    width="150px"
                    class-name="small-padding fixed-width"
                  >
                    <template #default="scope">
                      <el-button
                        
                        type="text"
                        icon="Edit"
                        @click="handlePropertyUpdate(scope.row)"
                        >修改</el-button
                      >
                      <el-popconfirm
                        title="确定删除此条属性吗?"
                        @confirm="handlePropertyDelete(scope.row)"
                      >
                        <template #reference>
                          <el-button  type="text" icon="Delete"
                            >删除</el-button
                          >
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog
        :title="propertyDialogParams.title"
        v-model="propertyDialogParams.show"
        width="600px"
        append-to-body
        destroy-on-close
      >
        <el-form
          :model="propertyForm"
          ref="propertyRef"
          :rules="propRules"
          label-width="120px"
        >
          <el-form-item label="属性名称" prop="name">
            <el-input
              v-model="propertyForm.name"
              placeholder="请输入属性名称"
            />
          </el-form-item>
          <el-form-item label="属性编码" prop="dataCode">
            <el-input
              v-model="propertyForm.dataCode"
              placeholder="请输入属性编码"
            />
          </el-form-item>
          <el-form-item label="属性类型" prop="kind">
            <el-select v-model="propertyForm.kind">
              <el-option
                v-for="item in kindList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="数据类型"
            prop="dataType"
            v-if="propertyForm.kind == 1"
          >
            <el-select v-model="propertyForm.dataType">
              <el-option
                v-for="item in dataTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

           <el-form-item
            label="统计类型"
            prop="statType"
            v-if="propertyForm.kind == 1"
          >
            <el-select v-model="propertyForm.statType">
              <el-option
                v-for="item in statTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>



          <el-form-item
            label="数据单位"
            prop="dataDw"
            v-if="propertyForm.kind == 1"
          >
            <el-input
              v-model="propertyForm.dataDw"
              placeholder="请输入属性编码"
            />
          </el-form-item>
          <el-form-item
            label="属性图标"
            prop="dataDw"
            v-if="propertyForm.kind == 1"
          >
            <el-upload
              class="avatar-uploader"
              action="/dev-api/common/oss/upload"
              :show-file-list="false"
              :headers="{
                'X-Noodle-Token': getToken(),
                Authorization: 'Bearer ' + getToken(),
              }"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="propertyForm.dataIcon"
                :src="propertyForm.dataIcon"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div style="font-size: 12px; color: #999">
                  仅支持 JPG/PNG 格式，大小不超过 500KB。<br />
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="属性默认值"
            prop="dataFormContent"
            v-if="propertyForm.kind == 0"
          >
            <el-input v-model="propertyForm.dataFormContent"></el-input>
          </el-form-item>
          <el-form-item
            label="系数"
            prop="dataMultiple"
            v-if="propertyForm.kind == 1"
          >
            <el-input
              v-model="propertyForm.dataMultiple"
              type="number"
              placeholder="请输入系数"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitProperty">确 定</el-button>
            <el-button @click="propertyForm.show = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 分页 -->
    <el-pagination
      style="float: right"
      @current-change="getList"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next"
      :total="pagination.total"
    />
  </div>
</template>

<script setup>
import {
  getDeviceTypeList,
  delDeviceType,
  getDeviceTypeDetailById,
  saveDeviceType,
} from "@/api/deviceType";
import {
  getPropertyList,
  delProperty,
  getPropertyDetailById,
  saveProperty,
} from "@/api/property";
import {
  getPropertyDataList,
  delPropertyData,
  getPropertyDataDetailById,
  savePropertyData,
} from "@/api/propertyData";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive } from "vue";

const { proxy } = getCurrentInstance();
const tableData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const kindList = [
  {
    label: "硬件属性",
    value: 0,
  },
  {
    label: "数据属性",
    value: 1,
  },
];
const deviceTypeEnumList = [
  {
    label: "水情",
    value: 100,
  },
  {
    label: "闸门",
    value: 200,
  },
  {
    label: "墒情",
    value: 300,
  },
  {
    label: "水质",
    value: 400,
  },
  {
    label: "气象",
    value: 500,
  },
  {
    label: "流量",
    value: 600,
  },
  {
    label: "泵站",
    value: 700,
  },
  {
    label: "摄像头",
    value: 800,
  },
];
const dataTypeList = [
  {
    label: "字符串",
    value: 0,
  },
  {
    label: "整数型",
    value: 1,
  },
  {
    label: "小数型",
    value: 2,
  },
  {
    label: "布尔型",
    value: 3,
  },
  {
    label: "日期型",
    value: 10,
  },
];
const statTypeList = [
  {
    label: "默认不统计",
    value: 0,
  },
  {
    label: "数字统计",
    value: 1,
  },
  {
    label: "差额数据统计",
    value: 2,
  },
];
const propertyForm = reactive({
  id: null,
  name: "",
  dataCode: "",
  dataType: 0,
  kind: 0,
  dataFormContent: "",
  dataMultiple: 1,
});
const propertyDialogParams = reactive({
  show: false,
  title: "新增属性",
});
const data = reactive({
  queryParams: {
    name: "",
  },
  rules: {
    name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    typeCode: [
      { required: true, message: "设备编码不能为空", trigger: "blur" },
    ],
  },
  propRules: {
    name: [{ required: true, message: "属性名称不能为空", trigger: "blur" }],
    dataCode: [
      { required: true, message: "属性编码不能为空", trigger: "blur" },
    ],
  },
});
const filterTag = (value, row) => {
  return row.kind === value;
};
function getTypeName(row) {
  return deviceTypeEnumList.find((f) => f.value == row.type).label;
}
const { queryParams, rules, propRules } = toRefs(data);
const form = reactive({});
const handleAvatarSuccess = (res, uploadFile) => {
  ElMessage({
    message: "上传成功！",
    type: "success",
  });
  propertyForm.dataIcon = res.data.fileUrl || res.data.link || res.data.url;
};
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt200k = file.size / 1024 < 500;

  if (!isJpgOrPng) {
    ElMessage.error("上传图片格式应为 JPG 或 PNG!");
  }
  if (!isLt200k) {
    ElMessage.error("上传图片大小不能超过 200KB!");
  }
  return isJpgOrPng && isLt200k;
};
function getNameByType(type) {
  return dataTypeList.filter((f) => f.value == type)[0].label;
}
function getStatNameByType(type) {
  return statTypeList.filter((f) => f.value == type)[0].label;
}
/** 查询列表 */
function getList() {
  loading.value = true;
  getDeviceTypeList({ ...pagination, ...queryParams.value }).then(
    (response) => {
      tableData.value = response.data.list;
      pagination.total = response.data.totalCount;
      console.log(tableData.value, response);
      loading.value = false;
    }
  );
}
function handlePropertyAdd() {
  propertyDialogParams.show = true;
  propertyDialogParams.title = "新增属性";
  Object.assign(propertyForm, {
    id: null,
    name: "",
    dataCode: "",
    dataType: 0,
    kind: 0,
    dataFormContent: "",
    dataDw: "",
    dataIcon: "",
    dataMultiple: 1,
    statType:0,
  });
}
function submitProperty() {
  proxy.$refs["propertyRef"].validate((valid) => {
    if (valid) {
      if (propertyForm.kind == 0) {
        propertyForm.dataType = 0; //硬件属性定死为string类型
        saveProperty(propertyForm).then((res) => {
          ElMessage.success("操作成功！");
          propertyDialogParams.show = false;
          updateDetail();
        });
      } else {
        saveProperty(propertyForm).then((res) => {
          ElMessage.success("操作成功！");
          propertyDialogParams.show = false;
          updateDetail();
        });
      }
    }
  });
}
function updateDetail() {
  getDeviceTypeDetailById(form.id).then((res) => {
    Object.assign(form, res.data);
  });
}
function handlePropertyUpdate(row) {
  Object.assign(propertyForm, row);
  propertyDialogParams.show = true;
  propertyDialogParams.title = "编辑属性";
}
function handlePropertyDelete(row) {
  if (row.kind == 0) {
    delProperty([row.id]).then((res) => {
      ElMessage.success("删除成功");
      updateDetail();
    });
  } else {
    delProperty([row.id]).then((res) => {
      ElMessage.success("删除成功");
      updateDetail();
    });
  }
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    id: null,
    kind: 0,
    type: 100,
    name: "",
    typeCode: "",
    dataFormType: 1,
    devicePropertyList: [],
    statType:0,
  });

  proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  open.value = true;
  title.value = "添加设备类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  getDeviceTypeDetailById(row.id).then((res) => {
    Object.assign(form, res.data);
    propertyForm.typeId = res.data.id;
    open.value = true;
    title.value = "修改设备属性";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      if (form.id) {
        saveDeviceType(form).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        saveDeviceType(form).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm(
    '是否确认删除名称为"' + row.name + '"的数据项?',
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      delDeviceType([row.id]).then((res) => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
}
getList();
</script>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
